class Solution:
    def minSwaps(self, grid: list) -> int:
        rights = [0 for _ in range(len(grid))]
        for i in range(len(grid)):
            for j in range(len(grid[i]) - 1, -1, -1):
                if grid[i][j] == 0:
                    rights[i] += 1
                else:
                    break
        ans = 0
        n = len(rights)
        for i in range(n):
            target = n - i - 1
            j = i
            while j < n and rights[j] < target:
                j += 1
            if j == n:
                return -1
            while j > i:
                temp = rights[j]
                rights[j] = rights[j - 1]
                rights[j - 1] = temp
                j -= 1
                ans += 1
        return ans


if __name__ == "__main__":
    # print(Solution().minSwaps([[0, 0, 1], [1, 1, 0], [1, 0, 0]]))
    # print(Solution().minSwaps([[1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0],
    #                            [1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0],
    #                            [1, 1, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0]]))
    print(Solution().minSwaps([[1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0],
                               [0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0],
                               [0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1]]))
